<template>
  <div class="dashboard-container">
    <!-- 核心业务指标统计卡片 -->
    <el-row :gutter="20" class="stat-cards">
      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover" class="stat-card stat-card-blue">
          <div class="stat-content">
            <div class="stat-icon">
              <i class="el-icon-office-building"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.shopCount || 0 }}</div>
              <div class="stat-label">店铺总数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover" class="stat-card stat-card-green">
          <div class="stat-content">
            <div class="stat-icon">
              <i class="el-icon-goods"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.productCount || 0 }}</div>
              <div class="stat-label">产品总数</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover" class="stat-card stat-card-orange">
          <div class="stat-content">
            <div class="stat-icon">
              <i class="el-icon-box"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ statistics.stockTotal || 0 }}</div>
              <div class="stat-label">剩余库存</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :lg="6">
        <el-card shadow="hover" class="stat-card stat-card-red">
          <div class="stat-content">
            <div class="stat-icon">
              <i class="el-icon-shopping-cart-2"></i>
            </div>
            <div class="stat-info">
              <div class="stat-value">¥{{ (statistics.purchaseAmountThisMonth || 0).toFixed(2) }}</div>
              <div class="stat-label">本月采购</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 采购趋势图 -->
      <el-col :xs="24" :lg="16">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>采购趋势（最近30天）</span>
          </div>
          <div ref="purchaseChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 产品状态分布 -->
      <el-col :xs="24" :lg="8">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>产品状态分布</span>
          </div>
          <div ref="statusChart" class="chart-container-pie"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 预警列表区域 -->
    <el-row :gutter="20">
      <!-- 库存预警列表 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>库存预警（剩余库存≤50）</span>
            <el-tag type="danger" size="mini" style="margin-left: 10px">紧急</el-tag>
          </div>
          <el-table 
            :data="stockWarningList" 
            style="width: 100%" 
            v-loading="loading"
            :empty-text="stockWarningList.length === 0 ? '暂无库存预警，库存充足' : ''"
            max-height="400"
          >
            <el-table-column type="index" label="#" width="50" align="center" />
            <el-table-column prop="sku" label="SKU" width="120" align="center" />
            <el-table-column prop="productName" label="产品名称" min-width="100" show-overflow-tooltip />
            <el-table-column prop="shopName" label="店铺" width="100" align="center" />
            <el-table-column prop="remainingStock" label="库存" width="80" align="center">
              <template slot-scope="scope">
                <el-tag 
                  :type="scope.row.remainingStock <= 20 ? 'danger' : (scope.row.remainingStock <= 50 ? 'warning' : 'success')"
                  size="small"
                >
                  {{ scope.row.remainingStock }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>

      <!-- 利润预警列表 -->
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>利润预警（利润率＜25%）</span>
            <el-tag type="warning" size="mini" style="margin-left: 10px">注意</el-tag>
          </div>
          <el-table 
            :data="profitWarningList" 
            style="width: 100%" 
            v-loading="loading"
            :empty-text="profitWarningList.length === 0 ? '暂无利润预警，利润健康' : ''"
            max-height="400"
          >
            <el-table-column type="index" label="#" width="50" align="center" />
            <el-table-column prop="sku" label="SKU" width="120" align="center" />
            <el-table-column prop="productName" label="产品名称" min-width="100" show-overflow-tooltip />
            <el-table-column prop="shopName" label="店铺" width="100" align="center" />
            <el-table-column prop="profitRate" label="利润率" width="90" align="center">
              <template slot-scope="scope">
                <el-tag 
                  :type="scope.row.profitRate < 0 ? 'danger' : (scope.row.profitRate < 15 ? 'danger' : 'warning')"
                  size="small"
                >
                  {{ scope.row.profitRate ? scope.row.profitRate.toFixed(2) : '0.00' }}%
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getStatistics, getPurchaseTrend, getProductStatus, getStockWarning, getProfitWarning } from '@/api/business/dashboard'
import * as echarts from 'echarts'

export default {
  name: 'Dashboard',
  data() {
    return {
      loading: false,
      statistics: {
        shopCount: 0,
        productCount: 0,
        stockTotal: 0,
        purchaseAmountThisMonth: 0
      },
      purchaseChart: null,
      statusChart: null,
      stockWarningList: [],
      profitWarningList: []
    }
  },
  mounted() {
    this.loadData()
  },
  beforeDestroy() {
    if (this.purchaseChart) {
      this.purchaseChart.dispose()
    }
    if (this.statusChart) {
      this.statusChart.dispose()
    }
  },
  methods: {
    /** 加载所有数据 */
    loadData() {
      this.loading = true
      Promise.all([
        this.loadStatistics(),
        this.loadPurchaseTrend(),
        this.loadProductStatus(),
        this.loadStockWarning(),
        this.loadProfitWarning()
      ]).finally(() => {
        this.loading = false
      })
    },

    /** 加载核心业务指标 */
    loadStatistics() {
      return getStatistics().then(response => {
        this.statistics = response.data
      })
    },

    /** 加载采购趋势并绘制图表 */
    loadPurchaseTrend() {
      return getPurchaseTrend().then(response => {
        const data = response.data || []
        this.$nextTick(() => {
          this.initPurchaseChart(data)
        })
      })
    },

    /** 加载产品状态分布并绘制图表 */
    loadProductStatus() {
      return getProductStatus().then(response => {
        const data = response.data || []
        this.$nextTick(() => {
          this.initStatusChart(data)
        })
      })
    },

    /** 加载库存预警列表 */
    loadStockWarning() {
      return getStockWarning().then(response => {
        this.stockWarningList = response.data || []
      })
    },

    /** 加载利润预警列表 */
    loadProfitWarning() {
      return getProfitWarning().then(response => {
        this.profitWarningList = response.data || []
      })
    },

    /** 初始化采购趋势图表 */
    initPurchaseChart(data) {
      if (!this.$refs.purchaseChart) return

      if (this.purchaseChart) {
        this.purchaseChart.dispose()
      }

      this.purchaseChart = echarts.init(this.$refs.purchaseChart)

      const dates = data.map(item => item.date)
      const amounts = data.map(item => parseFloat(item.amount || 0))

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>采购金额: ¥{c}'
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45,
            interval: Math.floor(dates.length / 10)
          }
        },
        yAxis: {
          type: 'value',
          name: '金额（元）',
          axisLabel: {
            formatter: '¥{value}'
          }
        },
        series: [
          {
            name: '采购金额',
            type: 'line',
            smooth: true,
            data: amounts,
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
                  { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
                ]
              }
            }
          }
        ],
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        }
      }

      this.purchaseChart.setOption(option)
    },

    /** 初始化产品状态分布图表 */
    initStatusChart(data) {
      if (!this.$refs.statusChart) return

      if (this.statusChart) {
        this.statusChart.dispose()
      }

      this.statusChart = echarts.init(this.$refs.statusChart)

      const chartData = data.map(item => ({
        name: item.statusName,
        value: item.count
      }))

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'horizontal',
          bottom: 10,
          left: 'center'
        },
        series: [
          {
            name: '产品状态',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: chartData,
            color: ['#67C23A', '#E6A23C', '#409EFF', '#F56C6C']
          }
        ]
      }

      this.statusChart.setOption(option)
    }
  }
}
</script>

<style scoped lang="scss">
.dashboard-container {
  padding: 20px;
  background-color: #f0f2f5;

  .stat-cards {
    margin-bottom: 20px;
  }

  .stat-card {
    margin-bottom: 20px;
    border-radius: 8px;
    overflow: hidden;

    &.stat-card-blue {
      background: linear-gradient(135deg, #5470C6 0%, #7389DC 100%);
    }

    &.stat-card-green {
      background: linear-gradient(135deg, #91CC75 0%, #A7D98E 100%);
    }

    &.stat-card-orange {
      background: linear-gradient(135deg, #FAC858 0%, #FBDB8E 100%);
    }

    &.stat-card-red {
      background: linear-gradient(135deg, #EE6666 0%, #F49898 100%);
    }

    ::v-deep .el-card__body {
      padding: 20px;
    }

    .stat-content {
      display: flex;
      align-items: center;
      color: #fff;

      .stat-icon {
        font-size: 48px;
        margin-right: 20px;
        opacity: 0.8;
      }

      .stat-info {
        flex: 1;

        .stat-value {
          font-size: 28px;
          font-weight: bold;
          margin-bottom: 5px;
        }

        .stat-label {
          font-size: 14px;
          opacity: 0.9;
        }
      }
    }
  }

  .chart-row {
    margin-bottom: 20px;
  }

  .card-header {
    font-weight: bold;
    font-size: 16px;
  }

  .chart-container {
    height: 350px;
  }

  .chart-container-pie {
    height: 350px;
  }
}
</style>
